package com.ojoin.trade.common.exception.web;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.commons.fileupload.FileUploadBase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import com.ojoin.trade.common.exception.BusinessException;
import com.ojoin.trade.common.exception.ControllerException;
import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.PrettyMemoryUtils;
import com.ojoin.trade.common.web.domain.Result;
import com.ojoin.trade.common.web.domain.Result.Status;

@ControllerAdvice
public class DefaultExceptionHandler {

	private Logger log = LoggerFactory.getLogger(DefaultExceptionHandler.class);

	/**
	 * 参数绑定异常
	 */
	@ExceptionHandler({BindException.class, ConstraintViolationException.class})
	@ResponseStatus(HttpStatus.OK)
	@ResponseBody
    public Result bindException(Exception e) { 
		String extraMsg="";
		if(e instanceof BindException){
			BindException be=(BindException)e;
			List<FieldError> fe=be.getBindingResult().getFieldErrors();
			extraMsg=CommonUtils.extractToString(fe,"rejectedValue",",");
		}
		LogUtils.error(log,e, e.getMessage());
		return new Result(false, String.format("参数绑定错误 %s",extraMsg));
    }
	
	/**
	 * 业务 异常
	 */
	@ExceptionHandler({ BusinessException.class })
	@ResponseStatus(HttpStatus.OK)
	@ResponseBody
	public Result processBusinessException(HttpServletRequest request,
			Exception e) {
		LogUtils.error(log, e.getMessage());
		return new Result(false, e.getMessage());
	}

	/**
	 * Control 异常
	 */
	@ExceptionHandler({ ControllerException.class })
	@ResponseStatus(HttpStatus.OK)
	@ResponseBody
	public Result processControllerException(HttpServletRequest request,
			Exception e) {
		LogUtils.error(log,e, e.getMessage());
		return new Result(false, e.getMessage());
	}

	
	@ExceptionHandler(MaxUploadSizeExceededException.class)
    @ResponseStatus(value = HttpStatus.OK)
    public void processSizeLimitException(HttpServletRequest request,HttpServletResponse response,
			Exception e) throws IOException {

		boolean isIE =CommonUtils.isIE(request);

		Long size=((FileUploadBase.SizeLimitExceededException)e.getCause()).getActualSize();
		if(isIE){
			CommonUtils.sendResponseMsg(response, new Result(Status.ERROR, "您上传的文件过大，" + PrettyMemoryUtils.prettyByteSize(size)));
		}   else{
			CommonUtils.sendJOSNResponse(response, new Result(Status.ERROR, "您上传的文件过大，" + PrettyMemoryUtils.prettyByteSize(size)));
		}
	}

	
	/**
	 * 未知 异常
	 */	 
	@ExceptionHandler({Exception.class })
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	public void processException(HttpServletRequest request,HttpServletResponse response,
			Exception e) throws IOException {
		
		LogUtils.error(log,e, e.getMessage());
		
		if(CommonUtils.isAjaxRequest(request)){
			CommonUtils.sendJOSNResponse(response, new Result(false, "服务异常,请稍后再试"));
		}else{
			response.sendRedirect("/error/error.html");
		}
	}

	 
	// 权限异常
	@ExceptionHandler({org.apache.shiro.authz.AuthorizationException.class })
	@ResponseStatus(HttpStatus.UNAUTHORIZED)
	public void AuthorizationException(HttpServletRequest request,
			HttpServletResponse response,
			Exception e) throws IOException {
		LogUtils.error(log,e, e.getMessage());
		
		if(CommonUtils.isAjaxRequest(request)){
			CommonUtils.sendJOSNResponse(response, new Result(false, e.getMessage()));
		}else{
			response.sendRedirect("/error/unauthorized.html");
		}
	}

}
